//
//  ResgisterUserVC.m
//  MRBang
//
//  Created by 铅笔 on 15/12/17.
//  Copyright © 2015年 杭州易网新科技. All rights reserved.
//

#import "ResgisterUserVC.h"
#import "RealNameVerificationVC.h"
#import "PrivacyController.h"

@interface ResgisterUserVC ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
{

     int starTime;
}

@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic,strong) UIScrollView *scrollView_bg;//滚动背景解决遮盖

@property (nonatomic,strong) UIButton *button_registerNow;//立即注册

@property (nonatomic,strong) UIButton *button_getCheckCode;//获取验证码

@property (nonatomic,strong) UITextField *textField_phone;
@property (nonatomic,strong) UITextField *textField_checkCode;
@property (nonatomic,strong) UITextField *textField_email;
@property (nonatomic,strong) UITextField *textField_pwd;
@property (nonatomic,strong) UITextField *textField_surepwd;
@property (nonatomic,strong) UITextField *textField_invitationCode;
@end

@implementation ResgisterUserVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"注册";
    
    //创建子视图
    [self initWithAllSubviews];
}

#pragma mark --- 创建视图
- (void) initWithAllSubviews
{
    //scrollView
    self.scrollView_bg = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    [self.view addSubview:self.scrollView_bg];
    self.scrollView_bg.showsVerticalScrollIndicator = NO;
    self.scrollView_bg.backgroundColor = RXDColor(238, 239, 241);
    
    if (IS_IPHONE_4_OR_LESS) {
       
        self.scrollView_bg.contentSize = CGSizeMake(kScreenWidth, kScreenHeight*1.2);
    }
    if (IS_IPHONE_5) {
        
        self.scrollView_bg.contentSize = CGSizeMake(kScreenWidth, kScreenHeight*1.1);
    }
    
    //tableView
    self.tableView = [[UITableView alloc] init];
    if (IS_IPHONE_4_OR_LESS || IS_IPHONE_5) {
        self.tableView.frame = CGRectMake(0,0,kScreenWidth, kScreenHeight);
       [self.scrollView_bg addSubview:self.tableView];
    }
    else
    {
        self.tableView.frame = CGRectMake(0,64,kScreenWidth, kScreenHeight);
       [self.view addSubview:self.tableView];
    }
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.backgroundColor = RXDColor(238, 239, 241);
    
    self.tableView.showsVerticalScrollIndicator = NO;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

#pragma mark ---- UITableViewDataSource
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 8;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     static NSString *ID = @"cellRegister";
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell==nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = RXDColor(238, 239, 241);
    
    if (indexPath.row!=0 && indexPath.row!=7) {
        
        NSArray *array_temp = @[@"  请输入手机号码",@"  请输入验证码",@"  请输入常用邮箱",@"  设置6-20位登录密码",@"  确认密码",@"  邀请码"];
        
        //设置背景
        UIView *view_everyBG = [[UIView alloc] initWithFrame:CGRectMake(20,0,kScreenWidth - 40, 70*PROPORTION_WIDTH)];
        [cell.contentView addSubview:view_everyBG];
        view_everyBG.backgroundColor = RXDColor(253, 253, 253);
        view_everyBG.layer.cornerRadius = 3.0;
        view_everyBG.clipsToBounds = YES;
        
        if (indexPath.row==1) {
           self.textField_phone = [[UITextField alloc] init];
            [view_everyBG addSubview:self.textField_phone];
            self.textField_phone.frame = CGRectMake(10, 0,view_everyBG.frame.size.width-70, view_everyBG.height);
            self.textField_phone.placeholder = array_temp[indexPath.row-1];
            self.textField_phone.keyboardType = UIKeyboardTypeNumberPad;
            self.textField_phone.returnKeyType = UIReturnKeyDone;
            self.textField_phone.delegate = self;
            self.textField_phone.font = [UIFont systemFontOfSize:Font_SIZE_22];
            
            [self.textField_phone addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

        }
        if (indexPath.row==2) {
            
            self.textField_checkCode = [[UITextField alloc] init];
            [view_everyBG addSubview:self.textField_checkCode];
            self.textField_checkCode.frame = CGRectMake(10, 0,view_everyBG.frame.size.width-70, view_everyBG.height);
            self.textField_checkCode.placeholder = array_temp[1];
            self.textField_checkCode.keyboardType = UIKeyboardTypeNumberPad;
            self.textField_checkCode.returnKeyType = UIReturnKeyDone;
            self.textField_checkCode.delegate = self;
            self.textField_checkCode.font = [UIFont systemFontOfSize:Font_SIZE_22];
            
            //button
            self.button_getCheckCode = [[UIButton alloc] initWithFrame:CGRectMake(view_everyBG.frame.size.width - 70, 0,70, view_everyBG.height)];
            [view_everyBG addSubview:self.button_getCheckCode];
            self.button_getCheckCode.backgroundColor = COLOR_BUTTON;
            [self.button_getCheckCode setTitle:@"获取验证码" forState:UIControlStateNormal];
            self.button_getCheckCode.layer.cornerRadius = 3.0;
            self.button_getCheckCode.clipsToBounds = YES;
            [self.button_getCheckCode.titleLabel setFont:[UIFont systemFontOfSize:Font_SIZE_18*2]];
            [self.button_getCheckCode.titleLabel setFont:[UIFont systemFontOfSize:13]];
            
            [self.button_getCheckCode addTarget:self action:@selector(startTime) forControlEvents:UIControlEventTouchUpInside];

        }
        if (indexPath.row==3) {
            self.textField_email = [[UITextField alloc] init];
            [view_everyBG addSubview:self.textField_email];
            self.textField_email.frame = CGRectMake(10, 0,view_everyBG.frame.size.width-70, view_everyBG.height);
            self.textField_email.placeholder = array_temp[2];
            
            self.textField_email.returnKeyType = UIReturnKeyDone;
            self.textField_email.delegate = self;
            self.textField_email.font = [UIFont systemFontOfSize:Font_SIZE_22];

        }
        if (indexPath.row==4) {
            self.textField_pwd = [[UITextField alloc] init];
            [view_everyBG addSubview:self.textField_pwd];
            self.textField_pwd.frame = CGRectMake(10, 0,view_everyBG.frame.size.width-70, view_everyBG.height);
            self.textField_pwd.secureTextEntry = YES;
            self.textField_pwd.placeholder = array_temp[3];
            
            self.textField_pwd.returnKeyType = UIReturnKeyDone;
            self.textField_pwd.delegate = self;
            self.textField_pwd.font = [UIFont systemFontOfSize:Font_SIZE_22];

        }
        if (indexPath.row==5) {
            
            self.textField_surepwd = [[UITextField alloc] init];
            [view_everyBG addSubview:self.textField_surepwd];
            self.textField_surepwd.frame = CGRectMake(10, 0,view_everyBG.frame.size.width-70, view_everyBG.height);
            self.textField_surepwd.secureTextEntry = YES;
            self.textField_surepwd.delegate = self;
            self.textField_surepwd.font = [UIFont systemFontOfSize:Font_SIZE_22];
            
            self.textField_surepwd.returnKeyType = UIReturnKeyDone;
            
            self.textField_surepwd.placeholder = array_temp[4];
        }
        if (indexPath.row==6)
        {
            self.textField_invitationCode = [[UITextField alloc] init];
            [view_everyBG addSubview:self.textField_invitationCode];
            self.textField_invitationCode.frame = CGRectMake(10, 0,view_everyBG.frame.size.width-70, view_everyBG.height);
            self.textField_invitationCode.secureTextEntry = YES;
            self.textField_invitationCode.delegate = self;
            self.textField_invitationCode.font = [UIFont systemFontOfSize:Font_SIZE_22];
            
            self.textField_invitationCode.returnKeyType = UIReturnKeyDone;
            
            self.textField_invitationCode.placeholder = array_temp[5];
        }
    }
    
    if (indexPath.row==7) {
    
        //设置修改button
        self.button_registerNow = [[UIButton alloc] initWithFrame:CGRectMake(20, 20,kScreenWidth - 40, 95*PROPORTION_WIDTH)];
        [cell addSubview:self.button_registerNow];
        self.button_registerNow.backgroundColor = RXDColor(255, 118, 112);
        [self.button_registerNow setTitle:@"立即注册" forState:UIControlStateNormal];
        self.button_registerNow.layer.cornerRadius = 3.0;
        self.button_registerNow.clipsToBounds = YES;
        [self.button_registerNow.titleLabel setFont:[UIFont systemFontOfSize:Font_SIZE_18*2]];
        
        [self.button_registerNow addTarget:self action:@selector(dataSourceRequestRegisterNow) forControlEvents:UIControlEventTouchUpInside];
        
        //label
        UILabel *label_text = [[UILabel alloc] initWithFrame:CGRectMake(20, self.button_registerNow.bottom+6,75, 20)];
        [cell.contentView addSubview:label_text];
        label_text.text = @"注册代表同意";
        label_text.font = [UIFont systemFontOfSize:12];
        label_text.textColor = RXDColor(189, 189, 189);
        
        //button
        UIButton *button_protocol = [[UIButton alloc] initWithFrame:CGRectMake(label_text.frame.size.width+20, label_text.frame.origin.y, 120, 20)];
        [cell addSubview:button_protocol];
        [button_protocol setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [button_protocol setTitle:@"《服务与隐私协议》" forState:UIControlStateNormal];
        [button_protocol.titleLabel setFont:[UIFont systemFontOfSize:12]];
        
        [button_protocol addTarget:self action:@selector(interIntoProtocolView) forControlEvents:UIControlEventTouchUpInside];

    }
    
    return cell;
}

/**
 *  网络协议
 */
- (void) interIntoProtocolView
{
    PrivacyController *privView = [[PrivacyController alloc] init];
    [self.navigationController pushViewController:privView animated:YES];

}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self commentTableViewTouchInSide];

}

//收回键盘
- (void)commentTableViewTouchInSide{
    [self.textField_checkCode resignFirstResponder];
    [self.textField_email resignFirstResponder];
    [self.textField_invitationCode resignFirstResponder];
    [self.textField_phone resignFirstResponder];
    [self.textField_pwd resignFirstResponder];
    [self.textField_surepwd resignFirstResponder];
}


- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        return 30;
    }
    if (indexPath.row==7) {
        return 220*PROPORTION_WIDTH;
    }
    else
    {
        return 100*PROPORTION_WIDTH;
    }
}

#pragma mark --- 立即注册 按钮
- (void) registerNowAction
{
    RealNameVerificationVC *realNameVerifVC = [[RealNameVerificationVC alloc] init];
    [self.navigationController pushViewController:realNameVerifVC animated:NO];
}

#pragma mark textfiled代理方法
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.textField_phone resignFirstResponder];
    [self.textField_checkCode resignFirstResponder];
    [self.textField_email resignFirstResponder];
    [self.textField_pwd resignFirstResponder];
    [self.textField_surepwd resignFirstResponder];
    [self.textField_invitationCode resignFirstResponder];
    return YES;
}

/**
 * 手机号码输入 长度
 */
- (void)textFieldDidChange:(UITextField *)textField
{
    if (textField == self.textField_phone) {
        if (self.textField_phone.text.length > 10 ) {
            self.textField_phone.text = [self.textField_phone.text substringToIndex:11];
        }
    }
}

#pragma mark - 倒计时

- (void)startTime
{
    
    if (self.textField_phone.text.length!=11) {
        [BaseViewController showMessage:@"请填写正确手机号"];
        
        [self.textField_phone resignFirstResponder];
        return;
    }

    if ([BaseViewController isMobileNumber_str:self.textField_phone.text] ) {
        [self dataSourceRequestGetCheckCode];
        
        starTime=60;
        //    __block int timeout=60; //倒计时时间
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
        dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
        dispatch_source_set_event_handler(_timer, ^{
            if(starTime<=0){ //倒计时结束，关闭
                dispatch_source_cancel(_timer);
                dispatch_async(dispatch_get_main_queue(), ^{
                    //设置界面的按钮显示 根据自己需求设置
                    [self.button_getCheckCode setTitle:@"重新发送" forState:UIControlStateNormal];
                    self.button_getCheckCode.userInteractionEnabled = YES;
                    self.button_getCheckCode.backgroundColor = COLOR_BUTTON;
                });
            }else{
                //            int minutes = timeout / 60;
                //            int seconds = timeout % 60;
                NSString *strTime = [NSString stringWithFormat:@"%.2d", starTime];
                dispatch_async(dispatch_get_main_queue(), ^{
                    //设置界面的按钮显示 根据自己需求设置
                    [self.button_getCheckCode setTitle:[NSString stringWithFormat:@"(%@)秒后\n重新发送",strTime] forState:UIControlStateNormal];
                    self.button_getCheckCode.backgroundColor = COLOR_UNBUTTON;
                    self.button_getCheckCode.titleLabel.numberOfLines=2;
                    self.button_getCheckCode.userInteractionEnabled = NO;
                });
                starTime--;
                
            }
        });
        dispatch_resume(_timer);

    }
    else
    {
        [UIView showAlertMsg:@"手机号码有误，请检查"];
    
    }
    [self.textField_phone resignFirstResponder];
}

#pragma mark ---- 立即注册网络请求
//获取短信验证码

- (void) dataSourceRequestGetCheckCode
{
    NSDictionary *paras_checkCode = @{@"mobile":self.textField_phone.text,@"type":[NSNumber numberWithInt:2]};
    NSString *strURL = [NSString stringWithFormat:@"%@captcha",MRAPI];

    [[HttpRequest shardWebUtil] postNetworkRequestURLString:strURL parameters:paras_checkCode success:^(id obj) {
        
        NSLog(@"obj%@",obj);
        NSString *str_false = obj[@"error"];
        
        if (str_false.length==0)
        {
            
        }
        else
        {
            [BaseViewController showMessage:str_false];
        }
    } fail:^(NSError *error) {
        
    }];
}

//立即注册
- (void) dataSourceRequestRegisterNow
{
    if (self.textField_email.text.length==0) {
        [BaseViewController showMessage:@"请填写邮箱"];
    }
    if (self.textField_pwd.text.length<6||self.textField_surepwd.text.length<6) {
        [BaseViewController showMessage:@"请填写正确密码"];
    }
    if (self.textField_pwd.text!=self.textField_surepwd.text) {
        [BaseViewController showMessage:@"两次密码不一致"];
    }
    else
    {
        NSDictionary *paras_register;
        
        if (self.textField_invitationCode) {
            //如果填写了邀请码
             paras_register = @{@"mobile":self.textField_phone.text,@"password":self.textField_pwd.text,@"email":self.textField_email.text,@"captcha":self.textField_checkCode.text,@"ycaptcha":self.textField_invitationCode.text};
        }
        else
        {
          paras_register = @{@"mobile":self.textField_phone.text,@"password":self.textField_pwd.text,@"email":self.textField_email.text,@"captcha":self.textField_checkCode.text};
        }
        
        NSString *strUrl = [NSString stringWithFormat:@"%@member/register",MRAPI];
        
        [[HttpRequest shardWebUtil] postNetworkRequestURLString:strUrl parameters:paras_register success:^(id obj) {
            
            NSString *str_false = obj[@"error"];
            if (str_false.length==0) {
                [BaseViewController showMessage:@"注册成功!"];
                [self.navigationController popViewControllerAnimated:YES];
            }
            else
            {
                [BaseViewController showMessage:str_false];
            }
            
        } fail:^(NSError *error) {
            
        }];
    }
    
    //键盘退出
//    [self.textField_phone resignFirstResponder];
//    [self.textField_checkCode resignFirstResponder];
//    [self.textField_email resignFirstResponder];
    [self.textField_invitationCode resignFirstResponder];
//    [self.textField_pwd resignFirstResponder];
//    [self.textField_surepwd resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
